<?php
namespace app\index\controller;

use app\common\controller\Helptype;
use app\index\common;
use app\index\controller\Dropdown;
use app\index\controller\Log\InsertLog as IL;
use app\index\controller\Log\OperationLog as OL;
use app\index\controller\Order;
use app\index\service\OrderService;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;

/**
 * 产品逻辑类
 */
class Product extends Controller {
	/**
	 * 2018-08-13
	 *
	 * 刘家腾
	 *
	 * 全网产品基础SQL where
	 *
	 * @param      string  $data      The data
	 * @param      string  $datalike  The datalike
	 * @param      string  $field     The field
	 */
	public function all_network_sql($data = '', $field_data = '', $page = '', $singlepage = '') {

		$product_data = Db::table('product')->alias('p')
			->join('store s', 'p.store_id=s.user_id', 'LEFT')
			->join('product_other po', 'p.id=po.product_id', 'LEFT')
			->join('staff st', 'st.user_id=p.staff_id', 'LEFT')
			->join('business b', 'p.business_id = b.business_id', 'LEFT')
			->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
			->join('warehouse_condition wc', 'p.is_shelf = wc.id', 'LEFT')
			->join('perchase_source ps', 'p.procurement_status = ps.id', 'LEFT')
			->join('product_state pst', 'pst.id = p.product_state', 'LEFT')
			->join('users u', 'u.id = p.business_id', 'LEFT')
			->join('merchant m', 'm.user_id = p.business_id', 'LEFT')
			->where($data)
			->order('p.network_time desc')
			->field($field_data)
			->paginate($singlepage, false, ['query' => request()->param()])
			->toArray();
		return $product_data;
	}

	/**
	 * [picture_list_network_sql 查询某个产品的所有图片]
	 * @DateTime 2018-09-06T13:46:21+0800
	 * @刘家腾
	 * @param    [type]                   $id [description]
	 * @return   [type]                       [description]
	 */
	public function picture_list_network_sql($id) {
		$productpic_data = Db::table('productpic')
			->where('product_id', $id)
			->where('state', 0)
			->select();
		return $productpic_data;
	}
	/**
	 * [is_synchronize_product 是否同步过]
	 * @DateTime 2018-09-06T13:38:40+0800
	 * @刘家腾
	 * @param    [type]                   $id [description]
	 * @return   boolean                      [description]
	 */
	public function is_synchronize_product($id = 0, $business_id = 0) {
		$productpic_data = Db::table('product')
			->where('source_product_id', $id)
			->where('business_id', $business_id)
			->where('state', 0)
			->count();

		return $productpic_data;
	}

	/**
	 * 2018-08-10
	 *
	 * 刘家腾
	 *
	 * 全网产品搜索
	 */
	public function all_network(Request $request) {
		$postData = $request->post();
		$user_info = Session::get('user');
		$data = array();
		$singlepage = 20;
		$page = 1;
		if ($user_info['is_business'] == 1) {
			$business_id = $user_info['id'];
		} else {
			$business_id = $this->business_id;
		}
		$data['p.state'] = 0;
		$data['p.business_id'] = array('neq', $business_id);
		$data['p.product_state'] = array('ELT', 4);
		if (!empty($postData['singlepage'])) {
			$singlepage = $postData['singlepage'];
		}
		if (empty($postData['is_network'])) {
			$data['p.is_network'] = array('eq', 1);
		} else {
			$data['p.is_network'] = array('eq', $postData['is_network']);
		}
		if (!empty($postData['category_id'])) {
			$data['p.category_id'] = array('eq', $postData['category_id']);
		}
		if (!empty($postData['is_shelf'])) {
			$data['p.is_shelf'] = array('eq', $postData['is_shelf']);
		}
		if (!empty($postData['page'])) {
			$page = $postData['page'];
		}
		if (!empty($postData['full_name'])) {
			$data['p.full_name'] = array('like', '%' . $postData['full_name'] . '%');
			$user_id = $this->user_id;
			Helptype::search_keyword($postData['full_name'], $user_id);
		}
		$field_data = 'p.id,p.product_condition,pf.value product_condition_value,p.pic_url,p.stock,p.product_name,p.product_sn,'
			. 's.store_name,p.is_shelf, wc.value shelf_value,po.shares,po.views,p.procurement_status,ps.value procurement_value,p.cost_price,'
			. 'p.additional,p.network_time,st.name,p.product_source,p.createtine,p.peer_price,p.price,p.library_age,p.coordinate,p.synopsis,p.full_name,p.thumb_url,p.pic_url,'

			. 'b.business_name,p.is_onsale,p.systematics_id,p.product_state,pst.value product_state_value,p.brand_id,p.type_id,p.category_id,p.source_product_id,p.is_autodeliver,p.is_synchro,p.delivery_id,u.phone,m.merShortName';
		$all_network_datas = $this->all_network_sql($data, $field_data, $page, $singlepage);
		$all_network_datas['sql'] = Db::table('product')->getLastSql();

		if (empty($all_network_datas['data'])) {
			return ['code' => 666, 'msg' => "没有查询到类似数据！", 'data' => null];
		}
		foreach ($all_network_datas['data'] as $key => $value) {

			$all_network_datas['data'][$key]['picture_list'] = $this->picture_list_network_sql($value['id']);
			$all_network_datas['data'][$key]['is_synchronize'] = $this->is_synchronize_product($value['id'], $business_id);
		}
		return ['code' => 666, 'msg' => "查询成功！", 'data' => $all_network_datas];

	}
	/**
	 * 2018-08-09
	 *
	 * 刘家腾
	 *
	 * 上下架  is_onsale ： 0 下架 / 1 上架
	 * @return     array  True if sale, False otherwise.
	 */
	public function is_sale(Request $request) {
		$postData = $request->post();
		$rules = [
			"id" => "require",
			"is_onsale" => "require",
		];
		if ($this->validate($postData, $rules) === true) {
			if(!in_array($postData['is_onsale'],[1,2])){
				return ['code' => -1, 'msg' => '上下架状态不对', 'data' => null];
			}
			if($postData['is_onsale']==2){
				$postData['is_onsale']=0;
			}
			return $this->is_sale_function($postData);
		} else {
			return ['code' => 30050, 'msg' => $this->validate($postData, $rules), 'data' => null];
		}
	}
	public function is_sale_function($postData) {
		$product = $this->validateSaleProduct($postData['id'], $postData['is_onsale']);
		if ($product['code'] != 666) {
			return $product;
		}
		$productData = $product['data'];
		//  如果是下架
		if ($postData['is_onsale'] == 0) {
				//下架商品
				Db::table('product')
					->where(['id' => $postData['id']])
					->update(['is_onsale' => 0,'updatetime'=>date('Y-m-d H:i:s',time())]);
		} else {
			//如果是上架
			if ($productData['is_synchro'] == 0) {
				//上架自己的商品
				Db::table('product')
					->where(['id' => $postData['id']])
					->update(['is_onsale' => 1,'is_offsale'=>1,'updatetime'=>date('Y-m-d H:i:s',time())]);
			} else {
				//如果不是自己的商品，要先看原来的商品是否在全网，是否删除，是否可售
				$product = Db::table('product')->where(['id' => $postData['id']])->find();
				$product_source = Db::table('product')->where(['id' => $product['source_product_id']])->find();
				if (!$product_source) {
					return ReturnData::error(3001, '原始商品不存在');
				} elseif ($product_source['state'] == 1) {
					return ReturnData::error(3001, '原始商品已删除');
				} elseif ($product_source['is_network'] == 0) {
					return ReturnData::error(3001, '原始商品未入全网');
				} elseif (!in_array($product_source['product_state'], [1, 2, 3, 4])) {
					return ReturnData::error(3001, '原始商品不在可售状态');
				} else {
					//可上架
					Db::table('product')
						->where(['id' => $postData['id']])
						->update(['is_onsale' => 1,'is_offsale'=>1,'updatetime'=>date('Y-m-d H:i:s',time())]);
				}
			}
		}
		$product_info = $this->product_info($postData['id']);

		if ($postData['is_onsale'] == 1) {
			// 创建消息通知
			$description = $product_info['data']['full_name'];
			OrderService::notice_add($this->user_id, 2, 1, $this->business_id, $postData['id'], $description);
			$msg = "上架成功！";
		} else {
			// 创建消息通知
			$description = $product_info['data']['full_name'];
			OrderService::notice_add($this->user_id, 3, 1, $this->business_id, $postData['id'], $description);
			$msg = "下架成功！";
		}
		return ['code' => 666, 'msg' => $msg, 'data' => null];
	}

	public function validateSaleProduct($id, $is_onsale) {
		$product = Db::table('product')
			->where(['id' => $id])
			->find();
		if ($product == null) {
			return ReturnData::error(3001, '该商品不存在');
		} elseif ($product['state'] == 1) {
			return ReturnData::error(3001, '该商品已禁用');
		} elseif (!in_array($product['product_state'], [1, 2, 3, 4])) {
			return ReturnData::error(3001, '该商品不在可售状态');
		}
		// elseif($product['business_id'] != $this->business_id){
		//     return ReturnData::error(3001,'该商品不是本商户商品');
		// }

		return ReturnData::ok($product);
	}

	/**
	 * 2018-08-09
	 *
	 * 刘家腾
	 *
	 * 是否入网  is_network: 0 否/1是
	 * @return     array  True if sale, False otherwise.
	 */
	public function is_network(Request $request) {
		$postData = $request->post();
		$rules = [
			"id" => "require",
			"is_network" => "require",
		];

		if ($this->validate($postData, $rules) === true) {
			if(!in_array($postData['is_network'],[1,2])){
				return ['code' => -1, 'msg' => '入全网状态不对', 'data' => null];
			}
			if($postData['is_network']==2){
				$postData['is_network']=0;
			}
			return $this->is_network_function($postData);
		} else {
			return ['code' => 30050, 'msg' => $this->validate($postData, $rules), 'data' => null];
		}
	}
	public function is_network_function($postData = '') {
		$product = $this->validateNetworkProduct($postData['id'], $postData['is_network']);
		if ($product['code'] != 666) {
			return $product;
		}
		try{
		//是否是同步商品
		if($product['data']['is_synchro'] ==1 ){
			return ['code' => -1, 'msg' => '非自有商品不可入网', 'data' => null];
		}else{
			//出全网
			if($postData['is_network']==0){
				//取消入网
				Db::table('product')
					->where(['id' => $postData['id']])
					->update(['is_network' =>0]);
				//如果商品被别人同步，下架别人同步商品
				Db::table('product')
					->where(['source_product_id' => $postData['id']])
					->update(['is_onsale' =>0,'is_sold_business' => 1]);
				$msg = "取消入网成功！";
			}else{
				Db::table('product')
					->where(['id' => $postData['id']])
					->update(['is_network' =>1,'re_network'=>1,'network_time'=>date('Y-m-d H:i:s',time())]);
				$msg = "入网成功！";
			}
		}
			return ['code' => 666, 'msg' => $msg, 'data' => null];

		}catch(Exception$e){
			return ['code' => -1, 'msg' => '入网失败'.$e, 'data' => null];
		}
	}

	public function validateNetworkProduct($id, $is_network) {
		$product = Db::table('product')
			->where(['id' => $id])
			->find();
		if ($product == null) {
			return ReturnData::error(3001, '该商品不存在');
		} elseif ($product['state'] == 1) {
			return ReturnData::error(3001, '该商品已禁用');
		} elseif (!in_array($product['product_state'], [1, 2, 3, 4])) {
			return ReturnData::error(3001, '该商品不在可售状态');
		} elseif ($product['business_id'] != $this->business_id) {
			return ReturnData::error(3001, '该商品不是本商户商品');
		}elseif($product['peer_price']>$product['price']){
			return ReturnData::error(3001, '入全网的商品销售价必须高于同行价');
		}
		return ReturnData::ok($product);
	}
	/***
		     * 2018-05-30
		     * 曹振威
		     * 获取所有类目/品牌/系列   (异步加载)
	*/

	public function systematics_list($systematics_id = 0, $type = 0) {
		if (empty($type)) {
			$where = [
				'system_id' => $this->system_id,
				'state' => 0,
				'superior_id' => $systematics_id,
			];
		} else {
			$where = [
				'system_id' => $this->system_id,
				'state' => 0,
				'type' => $type,
			];
		}
		$superior = Db::table('systematics')->where('id', $systematics_id)->field('id,superior_gene,type')->find();
		$superior_gene = $superior['superior_gene'] . '-' . $superior['id'];
		$superior_type = $superior['type'] + 1;
		$date_sql['type'] = $superior['type'] . ' | ' . $superior_gene;
		if ($superior['type'] > 1 && $superior_gene > 0) {
			$where['type'] = $superior_type;
			$where['superior_gene'] = $superior_gene;
		}
		$field = 'id,title';
		$row = Db::table('systematics')
			->where($where)
			->field($field)
			->select();
		foreach ($row as $key => $value) {
			if ($systematics_id == 0) {
				$letter = common::getfirstchar($value['title']);
			} else {
				$letter = '';
			}

			$standard = $this->standard_list($value['id']);

			$row[$key]['standard'] = $standard['data'];
			$row[$key]['initials'] = $letter;
		}

		$date = array('code' => 666, 'msg' => $date_sql, 'data' => $row);
		IL::insert('log', [
			'user_id' => $this->user_id,
			'operation_user' => $this->user['name'],
			'operation_name' => '查看',
			'operation_content' => '查看类目/品牌/系列',
			'operation_type' => 1,
			'ip' => Request()->ip(),
			'state' => 1,
			'createtime' => date('Y-m-d H:i:s'),
		]);
		return $date;
	}

	/**
	 * 2018-05-04
	 * 曹振威
	 * 规格列表
	 */
	public function standard_list($systematics_id = 0) {
		$where = [
			'system_id' => $this->system_id,
			'state' => 0,
			'systematics_id' => $systematics_id,
		];
		$field = 'id,title';
		$row = Db::table('standard')->where($where)->field($field)->select();
		$date = array('code' => 666, 'msg' => '规格列表获取成功', 'data' => $row);
		IL::insert('log', [
			'user_id' => $this->user_id,
			'operation_user' => $this->user['name'],
			'operation_name' => '查看',
			'operation_content' => '查看规格列表',
			'operation_type' => 1,
			'ip' => Request()->ip(),
			'state' => 1,
			'createtime' => date('Y-m-d H:i:s'),
		]);
		return $date;
	}

	/**
	 * 2018-4-18 日期格式
	 * 2018-05-30  修改
	 * 曹振威 开发人
	 * 删除类目
	 */
	public function systematics_delete($id = 0) {
		if (!$id) {
			$date = array('code' => 20021, 'msg' => '非法操作', 'data' => '');
			exit(json_encode($date));
		}
		$where = [
			'id' => $id,
			'system_id' => $this->system_id,
		];
		$row = Db::table('systematics')->where($where)->setField('state', 1);
		if ($row) {
			$date = array('code' => 666, 'msg' => '删除类目成功', 'data' => '');
			IL::insert('log', [
				'user_id' => $this->user_id,
				'operation_user' => $this->user['name'],
				'operation_name' => '删除',
				'operation_content' => '删除类目/品牌/系列成功',
				'operation_type' => 3,
				'ip' => Request()->ip(),
				'state' => 1,
				'createtime' => date('Y-m-d H:i:s'),
			]);
		} else {
			$date = array('code' => 20037, 'msg' => '删除类目失败', 'data' => '');
			IL::insert('log', [
				'user_id' => $this->user_id,
				'operation_user' => $this->user['name'],
				'operation_name' => '删除',
				'operation_content' => '删除类目/品牌/系列失败',
				'operation_type' => 3,
				'ip' => Request()->ip(),
				'state' => 0,
				'createtime' => date('Y-m-d H:i:s'),
			]);
		}
		return $date;
	}

	/**
	 * 2018-05-30
	 * czw
	 * 获取父级类目的基因
	 */
	public function get_superior_gene($systematics_id) {
		if ($systematics_id) {
			$row = Db::table('systematics')->where('id', $systematics_id)->value('superior_gene');
			if ($row == 0) {
				return $systematics_id;
			} else {
				return $row . '-' . $systematics_id;
			}
		} else {
			return 0;
		}
	}

	/**
	 * 2018-4-17 日期格式
	 * 2018-05-30  修改
	 * 曹振威 开发人
	 * 添加/修改类目
	 */
	public function systematics_add_edit($superior_id = 0, $title = '', $id = 0) {
		//$systematics_id = 0 添加父级类目   有值   添加下级类目   基因  为父级基因加上父级
		if (!$title) {
			$date = array('code' => 20099, 'msg' => '类目名称（title）不能为空', 'data' => '');
			exit(json_encode($date));
		}
		$superior_gene = $this->get_superior_gene($superior_id);
		$systematics_insert = [
			'system_id' => $this->system_id,
			'superior_id' => $superior_id,
			'superior_gene' => $superior_gene,
			'title' => $title,
			'createtime' => date('Y-m-d H:i:s'),
		];
		$where['system_id'] = $this->system_id;
		if ($systematics_insert) {
			if ($id) {
				// 编辑
				$where['id'] = $id;
				$row_type = 1;
				$row = Db::table('systematics')->where($where)->update($systematics_insert);
			} else {
				// 添加
				$row_type = 2;
				$row = Db::table('systematics')->insert($systematics_insert);
			}

			if ($row) {
				if ($row_type == 1) {
					$date = array('code' => 666, 'msg' => '编辑类目成功', 'data' => '');
					IL::insert('log', [
						'user_id' => $this->user_id,
						'operation_user' => $this->user['name'],
						'operation_name' => '编辑',
						'operation_content' => '编辑类目/品牌/系列成功',
						'operation_type' => 2,
						'ip' => Request()->ip(),
						'state' => 1,
						'createtime' => date('Y-m-d H:i:s'),
					]);
				} elseif ($row_type == 2) {
					$date = array('code' => 666, 'msg' => '添加类目成功', 'data' => '');
					IL::insert('log', [
						'user_id' => $this->user_id,
						'operation_user' => $this->user['name'],
						'operation_name' => '添加',
						'operation_content' => '添加类目/品牌/系列成功',
						'operation_type' => 2,
						'ip' => Request()->ip(),
						'state' => 1,
						'createtime' => date('Y-m-d H:i:s'),
					]);
				}

			} else {
				if ($row_type == 1) {
					$date = array('code' => 20036, 'msg' => '编辑类目失败', 'data' => '');
					IL::insert('log', [
						'user_id' => $this->user_id,
						'operation_user' => $this->user['name'],
						'operation_name' => '编辑',
						'operation_content' => '编辑类目/品牌/系列失败',
						'operation_type' => 2,
						'ip' => Request()->ip(),
						'state' => 0,
						'createtime' => date('Y-m-d H:i:s'),
					]);
				} elseif ($row_type == 2) {
					$date = array('code' => 20036, 'msg' => '添加类目失败', 'data' => '');
					IL::insert('log', [
						'user_id' => $this->user_id,
						'operation_user' => $this->user['name'],
						'operation_name' => '添加',
						'operation_content' => '添加类目/品牌/系列失败',
						'operation_type' => 2,
						'ip' => Request()->ip(),
						'state' => 0,
						'createtime' => date('Y-m-d H:i:s'),
					]);
				}
			}
		}
		return $date;
	}

	/**
	 * 2018-4-18 日期格式
	 * 曹振威 开发人
	 * 单个删除规格
	 */
	public function standard_del($id = 0) {
		if (!$id) {
			$date = array('code' => 20021, 'msg' => '非法操作', 'data' => '');
			exit(json_encode($date));
		}
		$where = [
			'id' => $id,
			'system_id' => $this->system_id,
		];
		$row = Db::table('standard')->where($where)->setField('state', 1);
		if ($row) {
			$date = array('code' => 666, 'msg' => '删除规格成功', 'data' => '');
			IL::insert('log', [
				'user_id' => $this->user_id,
				'operation_user' => $this->user['name'],
				'operation_name' => '删除',
				'operation_content' => '删除规格成功',
				'operation_type' => 3,
				'ip' => Request()->ip(),
				'state' => 1,
				'createtime' => date('Y-m-d H:i:s'),
			]);
		} else {
			$date = array('code' => 20035, 'msg' => '删除规格失败', 'data' => '');
			IL::insert('log', [
				'user_id' => $this->user_id,
				'operation_user' => $this->user['name'],
				'operation_name' => '删除',
				'operation_content' => '删除规格失败',
				'operation_type' => 3,
				'ip' => Request()->ip(),
				'state' => 0,
				'createtime' => date('Y-m-d H:i:s'),
			]);
		}
		return $date;
	}

	/**
	 * 2018-4-17 日期格式
	 * 曹振威 开发人
	 * 单个添加/修改规格
	 */
	public function standard_add_eidt($title = '', $systematics_id = 0, $id = 0) {
		if (!$title) {
			$date = array('code' => 20098, 'msg' => '规格名称（title）必须填写', 'data' => '');
			exit(json_encode($date));
		}
		if (!$systematics_id) {
			$date = array('code' => 20098, 'msg' => '规格所属的类目需要填写哦', 'data' => '');
			exit(json_encode($date));
		}
		$stand_insert = [
			'system_id' => $this->system_id,
			'systematics_id' => $systematics_id,
			'title' => $title,
			'createtime' => date('Y-m-d H:i:s'),
		];
		if ($id) {
			// 编辑模式
			$where['system_id'] = $system_id;
			$where['id'] = $id;
			$row_type = 1;
			$row = Db::table('standard')->where($where)->update($stand_insert);
		} else {
			// 添加模式
			$row_type = 2;
			$row = Db::table('standard')->insert($stand_insert);
		}
		if ($row) {
			if ($row_type == 1) {
				$date = array('code' => 666, 'msg' => '编辑规格成功', 'data' => '');
				IL::insert('log', [
					'user_id' => $this->user_id,
					'operation_user' => $this->user['name'],
					'operation_name' => '编辑',
					'operation_content' => '编辑规格成功',
					'operation_type' => 2,
					'ip' => Request()->ip(),
					'state' => 1,
					'createtime' => date('Y-m-d H:i:s'),
				]);
			} elseif ($row_type == 2) {
				$date = array('code' => 666, 'msg' => '操作成功', 'data' => '');
				IL::insert('log', [
					'user_id' => $this->user_id,
					'operation_user' => $this->user['name'],
					'operation_name' => '编辑',
					'operation_content' => '编辑规格失败',
					'operation_type' => 2,
					'ip' => Request()->ip(),
					'state' => 0,
					'createtime' => date('Y-m-d H:i:s'),
				]);
			}
		} else {
			if ($row_type == 1) {
				$date = array('code' => 20034, 'msg' => '添加规格', 'data' => '');
				IL::insert('log', [
					'user_id' => $this->user_id,
					'operation_user' => $this->user['name'],
					'operation_name' => '添加',
					'operation_content' => '添加规格失败',
					'operation_type' => 2,
					'ip' => Request()->ip(),
					'state' => 1,
					'createtime' => date('Y-m-d H:i:s'),
				]);
			} elseif ($row_type == 2) {
				$date = array('code' => 20034, 'msg' => '添加规格', 'data' => '');
				IL::insert('log', [
					'user_id' => $this->user_id,
					'operation_user' => $this->user['name'],
					'operation_name' => '添加',
					'operation_content' => '添加规格成功',
					'operation_type' => 2,
					'ip' => Request()->ip(),
					'state' => 0,
					'createtime' => date('Y-m-d H:i:s'),
				]);
			}
		}
		return $date;
	}

	/**
	 * 2018-05-31
	 * czw
	 * 根据产品品牌和系列生成产品名称
	 */
	public function set_product_name($systematics_id = 0) {
		$systematics_arr = $this->get_systematics($systematics_id);
		if (array_key_exists('xilie', $systematics_arr)) {
			$product_name = $systematics_arr['brand']['title'] . '/' . $systematics_arr['xilie']['title'];
		} elseif (array_key_exists('brand', $systematics_arr)) {
			$product_name = $systematics_arr['brand']['title'];
		} else {
			$product_name = '';
		}
		$date = array('code' => 666, 'msg' => '产品名称生成成功', 'data' => $product_name);
		return $date;
	}

	/**
	 *
	 * 2018-4-12 日期格式
	 * 2018-05-30 修改
	 * 曹振威 开发人
	 * 产品发布/更新
	 * @param Request $Request
	 * @return
	 */
	public function add_edit_product(Request $R) {
		$post = $R->post();
		$rule = [
			'image' => 'require|array|min:1',
			'product_cate' => 'require|number',
			'product_condition' => 'require|number|between:1,7',
			'is_shelf' => 'require|number|between:1,11',
			'procurement_status' => 'require|number|between:1,4',
			'product_sn' => 'require',
            'synopsis'  => 'require',
			'systematics' => 'require|array',
			'stock' => 'require|number|between:1,120',
			'price' => 'require|float|gt:0',
			'peer_price' => 'require|float|gt:0',
		];
		$message = [
			'image.require' => '商品图片记得上传',
			'image.array' => '商品图片是数组形式',
			'image.min' => '必须上传至少一张商品图片',
			'product_cate.require' => '商品类型要选择',
			'product_cate.number' => '商品类型传数字',
			'product_condition.require' => '商品成色要选择',
			'product_condition.number' => '商品成色必须传数字',
			'product_condition.between' => '商品成色必须传1-7数字',
			'is_shelf.require' => '库存状态必填',
			'is_shelf.number' => '库存状态必须传数字',
			'is_shelf.between' => '库存状态必须传1-11的数字',
			'procurement_status.require' => '采购类别必选',
			'procurement_status.number' => '采购类别必须传数字',
			'procurement_status.between' => '采购类别必须传1-4数字',
			'product_sn.require' => '商品货号不能空着，请选择商品类别，系统自动生成货号',
			'systematics.require' => '商品类别必填',
			'systematics.array' => '商品类别必须传数组',
            'synopsis.require'  => '商品描述不能为空',
			'stock.require' => '商品数量必填',
			'stock.number' => '商品数量必须是数字',
			'stock.between' => '商品数量必须在1-120中间',
			'price.require' => '销售价必填',
			'price.float' => '销售价是浮点类型',
			'price.gt' => '销售价必须大于0',
			'peer_price.require' => '同行价必填',
			'peer_price.float' => '同行价是浮点类型',
			'peer_price.gt' => '同行价必须大于0',
		];
		$bool = $this->validate($post, $rule, $message);
		if ($bool !== true) {
			exit(json_encode(array('code' => 20101, 'msg' => $bool, 'data' => '')));
		}
		$phone = common::check_mobile($post['product_source']);
		if ($phone['ErrorCode'] > 0) {
			$date = array('code' => 20003, 'msg' => '要填手机号', 'data' => '');
			exit(json_encode($date));
		}
		$product_img = array();
		$files = $post['image'];
		if (array_key_exists('1', $files)) {
			foreach ($files as $file) {
				$product_img[] = $file;
			}
		} else {
			$product_img[] = $files[0];
		}
		$product_state = $this->warehouse_product($post['is_shelf']);
		$qiniuConfig = Config::get('qiniu');
		if (strstr($product_img[0], 'http:')) {
			$pic_url = $product_img[0];
			$thumb_url = $product_img[0] . $qiniuConfig['thumbnail'];
		} else {
			$pic_url = $qiniuConfig['domainName'] . $product_img[0];
			$thumb_url = $qiniuConfig['domainName'] . $product_img[0] . $qiniuConfig['thumbnail'];
		}
		$product_insert = [
			'pic_url' => $pic_url,
			'thumb_url' => $thumb_url,
			'system_id' => $this->system_id,
			'business_id' => $this->business_id,
			'price' => $post['price'],
			'peer_price' => $post['peer_price'],
			'stock' => $post['stock'],
			'procurement_status' => $post['procurement_status'],
			'is_shelf' => $post['is_shelf'],
			// 'is_network'   => isset($post['is_network'])? $post['is_network']: 0,
			'product_condition' => $post['product_condition'],
			'product_state' => intval($product_state),
			'product_code' => $post['product_code'],
			'product_cate' => $post['product_cate'],
			'network_time' => isset($post['is_network']) ? date('Y-m-d H:i:s') : '',
		];
		if (isset($post['parts'])) {
			$product_insert['parts'] = $post['parts'];
		}
		if (isset($post['systematics']['id'])) {
			$arr_systematics = $this->get_systematics($post['systematics']['id']);
			if (!$arr_systematics) {
				exit(json_encode(['code' => 20727, 'msg' => '类目必填', 'data' => '']));
			} else {
				if (array_key_exists('systematics', $arr_systematics)) {
					$product_insert['category_id'] = $arr_systematics['systematics']['id'];
				}
				if (array_key_exists('child_systematics', $arr_systematics)) {
					$product_insert['type_id'] = $arr_systematics['child_systematics']['id'];
				}
				if (array_key_exists('brand', $arr_systematics)) {
					$product_insert['brand_id'] = $arr_systematics['brand']['id'];
				}
				if (array_key_exists('xilie', $arr_systematics)) {
					$product_insert['systematics_id'] = $arr_systematics['xilie']['id'];
				}
			}
		}
		$product_name = $this->set_product_name($post['systematics']['id']);
		if (($post['product_cate'] == 0 && $post['product_condition'] == 7) || ($post['product_cate'] == 1 && $post['product_condition'] != 7)) {
			exit(json_encode(array('code' => 20001, 'msg' => '产品类型和产品成色冲突', 'data' => '')));
		}
		if (!$product_name['data'] && !$post['product_name']) {
			exit(json_encode(array('code' => 20201, 'msg' => '产品名称必填', 'data' => '')));
		} else {
			$product_insert['product_name'] = $post['product_name'];
			$product_insert['full_name'] = $this->getProductConditionValue($post['product_condition']) . ' ' . $product_name['data'] . ' ' . $post['product_name'];
		}
		//上下架状态,前台传入为1，2
		if($post['is_onsale']==2){
			$post['is_onsale']=0;
		}
		//入全网状态,前台传入为1，2
		if($post['is_network']==2){
			$post['is_network']=0;
		}
		if (!$post['store_id']) {
			$product_insert['store_id'] = $this->store_id;
		} else {
			$product_insert['store_id'] = $post['store_id'];
		}
		if (!$post['staff_id']) {
			$product_insert['staff_id'] = $this->user_id;
		} else {
			$product_insert['staff_id'] = $post['staff_id'];
		}
		if ($post['product_source']) {
			$source = Db::table('users')->where('phone', $post['product_source'])->find();
			if (empty($source)) {
				$customer = $this->insert_user_customer($post['product_source'], $product_insert['staff_id']);
				$product_insert['origin_id'] = $customer;
				$product_insert['product_source'] = $post['product_source'];
			} else {
				$product_insert['origin_id'] = $source['id'];
				$product_insert['product_source'] = $post['product_source'];
			}
		}
		if ($post['cost_price']) {
			$product_insert['cost_price'] = $post['cost_price'];
		}
		if ($post['product_cate'] == 1) {
			$product_insert['product_condition'] = 7;
		} else {
			$product_insert['product_condition'] = $post['product_condition'];
		}
		if (isset($post['additional'])) {
			$product_insert['additional'] = $post['additional'];
		}
		if ($post['maintenance'] == '') {
			$product_insert['maintenance'] = 2;
		} else {
			$product_insert['maintenance'] = $post['maintenance'];
		}
		if ($post['coordinate']) {
			$product_insert['coordinate'] = $post['coordinate'];
		}
		if ($post['library_age']) {
			$product_insert['library_age'] = $post['library_age'];
		} else {
			$product_insert['library_age'] = 0;
		}
		if ($post['synopsis']) {
			$product_insert['synopsis'] = $post['synopsis'];
		}
		$standard_arr = $this->standard_attr($post['systematics']);
		if ($standard_arr) {
			$product_insert['standard_id'] = $standard_arr['standard'];
		}
		if ($post['remark']) {
			$product_insert['remark'] = $post['remark'];
		}
		if($post['is_network']>0){
			if($post['peer_price']>$post['price']){
				$date = array('code' => -1, 'msg' => '入全网的商品销售价必须高于同行价', 'data' => '');
				return $date;
			}
		}
		if (!$post['product_sn']) {
			$date = array('code' => 20089, 'msg' => '产品货号不能为空。', 'data' => '');
			exit(json_encode($date));
		} elseif (isset($post['id'])) {
			$row_product_sn = Db::table('product')->where(array('id' => $post['id'], 'product_sn' => $post['product_sn']))->find();
			if (!$row_product_sn) {
				$date = array('code' => 20094, 'msg' => '产品货号不能改变。', 'data' => '');
				exit(json_encode($date));
			}
		} else {
			$row_product_sn = Db::table('product')->where('product_sn', $post['product_sn'])->find();
			if ($row_product_sn) {
				$date = array('code' => 20094, 'msg' => '产品货号已存在，请重新填写或生成。', 'data' => '');
				exit(json_encode($date));
			}
		}
		if (array_key_exists('id', $post)) {
			if (!empty($post['id'])) {
				$product_id = $post['id'];
				$where['product_id'] = $product_id;
				OrderService::check_order($product_id, $this->business_id);
				$this_business_id = $this->business_id;

				if (!empty($post['peer_price']) && $post['is_network'] == 1) {
					//如果是自有商品 并且在全网里 同行价不能改为比原来的低
					OrderService::check_issold_business($product_id, $post['peer_price']);
				}

				Db::startTrans();
				try {
					$product_insert['updatetime'] = date('Y-m-d H:i:s');
					$data = Db::table('product')->where(array('id' => $post['id'], 'product_sn' => $post['product_sn']))->update($product_insert);
					$this->edit_product_image($product_id, $where, $product_img); // 编辑商品图片
					$this->edit_attr($standard_arr, $product_id, $where); // 编辑产品属性
					Db::commit();
					$saledate['id'] = $post['id'];
					$saledate['is_onsale'] = $post['is_onsale'];
					$this->is_sale_function($saledate);

					$networkdata['id'] = $post['id'];
					$networkdata['is_network'] = $post['is_network'];
					$this->is_network_function($networkdata);
					// 创建消息通知
					$description = '  ' . $product_insert['full_name'];
					OrderService::notice_add($this->user_id, 4, 1, $this->business_id, $product_id, $description, 1, 0);
					$date = array('code' => 666, 'msg' => '编辑商品成功', 'data' => '');
					OL::insert([
						'user_id' => $this->user_id,
						'module' => 'product',
						'module_id' => $product_id,
						'operation_type' => 2,
						'operation_content' => json_encode([
							'product' => Db::table('product')->where(['id' => $post['id']])->find(),
						]),
					]);
				} catch (Exception $exc) {
					// 回滚事务
					Db::rollback();
					$date = array('code' => 20022, 'msg' => '编辑商品失败' . $exc, 'data' => '1');
				}
			}
		} else {
			Db::startTrans();
			try {
				$product_insert['createtine'] = date('Y-m-d H:i:s');
				$product_insert['updatetime'] = date('Y-m-d H:i:s');
				$product_insert['product_sn'] = $post['product_sn'];
				$product_id = Db::table('product')->insertGetId($product_insert);
				$this->add_product_image($product_id, $product_img); // 添加商品图片
				$this->add_attr($standard_arr, $product_id); // 添加产品属性
				// 提交事务
				Db::commit();

				$saledate['id'] = $product_id;
				$saledate['is_onsale'] = $post['is_onsale'];
				$this->is_sale_function($saledate);

				$networkdata['id'] = $product_id;
				$networkdata['is_network'] = $post['is_network'];
				$this->is_network_function($networkdata);
				// 创建消息通知
				$description = $product_insert['full_name'];
				OrderService::notice_add($this->user_id, 1, 1, $this->business_id, $product_id, $description, 1, 0);

				$product_sx['product_id'] = $product_id;
				$date = ['code' => 666, 'msg' => '添加商品成功', 'data' => $product_sx];
				OL::insert([
					'user_id' => $this->user_id,
					'module' => 'product',
					'module_id' => $product_id,
					'operation_type' => 1,
					'operation_content' => json_encode(['product' => Db::table('product')->where(['id' => $product_id])->find()]),
				]);
			} catch (Exception $exc) {
				// 回滚事务
				Db::rollback();
				$date = array('code' => 20022, 'msg' => '添加商品失败' . $exc, 'data' => '');
			}
		}
		return $date;
	}

	public function getProductConditionValue($key) {
		$product_fineness = Db::table('product_fineness')->where(['id' => $key])->field('value')->find();
		return $product_fineness['value'];
	}

	/**
	 * 2018-05-30
	 * czw
	 * 添加产品属性
	 */

	public function add_attr($standard_arr = array(), $product_id = 0) {
		if (!$product_id) {
			$date = array('code' => 20104, 'msg' => '添加属性的产品id', 'data' => '');
			exit(json_encode($date));
		}
		if (array_key_exists('attr', $standard_arr) && !empty($standard_arr['attr'])) {
			foreach ($standard_arr['attr'] as $k_attr => $v_attr) {
				$attr_insert[] = [
					'product_id' => $product_id,
					'standard_id' => $v_attr['standard_id'],
					'title' => $v_attr['title'],
					'createtime' => date('Y-m-d H:i:s'),
				];
			}
			$date = Db::table('attributevalue')->insertAll($attr_insert);
			IL::insert('log', [
				'user_id' => $this->user_id,
				'operation_user' => $this->user['name'],
				'operation_name' => '添加',
				'operation_content' => '添加产品属性成功',
				'operation_type' => 2,
				'ip' => Request()->ip(),
				'createtime' => date('Y-m-d H:i:s'),
				'state' => 1,
			]);
		} else {
			$date = array();
		}
		return $date;
	}

	/**
	 * 2018-05-30
	 * czw
	 * 编辑产品属性
	 */

	public function edit_attr($standard_arr = array(), $product_id = 0, $where = array()) {
		if (!$product_id) {
			$date = array('code' => 20104, 'msg' => '添加属性的产品id', 'data' => '');
			exit(json_encode($date));
		}
		if (array_key_exists('attr', $standard_arr) && !empty($standard_arr['attr'])) {
			foreach ($standard_arr['attr'] as $k_attr => $v_attr) {
				$attr_insert[] = [
					'product_id' => $product_id,
					'standard_id' => $v_attr['standard_id'],
					'title' => $v_attr['title'],
					'createtime' => date('Y-m-d H:i:s'),
				];
			}
			try {
				Db::table('attributevalue')->where($where)->setField('state', 1);
				$date = Db::table('attributevalue')->insertAll($attr_insert);
				Db::commit();
				IL::insert('log', [
					'user_id' => $this->user_id,
					'operation_user' => $this->user['name'],
					'operation_name' => '编辑',
					'product_id' => $product_id,
					'operation_content' => '编辑产品属性成功',
					'operation_type' => 2,
					'ip' => Request()->ip(),
					'createtime' => date('Y-m-d H:i:s'),
					'state' => 1,
				]);
			} catch (Exception $exc) {
				Db::rollback();
				IL::insert('log', [
					'user_id' => $this->user_id,
					'operation_user' => $this->user['name'],
					'operation_name' => '编辑',
					'product_id' => $product_id,
					'operation_content' => '编辑产品属性失败',
					'operation_type' => 2,
					'ip' => Request()->ip(),
					'createtime' => date('Y-m-d H:i:s'),
					'state' => 0,
				]);
			}
		} else {
			$date = array();
		}
		return $date;
	}

	/**
	 * 2018-05-30
	 * czw
	 * 添加商品图片
	 */

	public function add_product_image($product_id = 0, $image = array()) {
		$img_insert = array();
		$qiniuConfig = Config::get('qiniu');
		if (!$product_id || !$image[0]) {
			$date = array('code' => 20102, 'msg' => '添加图片的产品id，和要添加的图片不能为空', 'data' => '');
			exit(json_encode($date));
		} else {
			foreach ($image as $val) {
				if (strstr($val, 'http:')) {
					$pic_url = $val;
					$thumb_url = $val . $qiniuConfig['thumbnail'];
				} else {
					$pic_url = $qiniuConfig['domainName'] . $val;
					$thumb_url = $qiniuConfig['domainName'] . $val . $qiniuConfig['thumbnail'];
				}
				$img_insert[] = [
					'product_id' => $product_id,
					'pic_url' => $pic_url,
					'thumb_url' => $thumb_url,
					'createtime' => date('Y-m-d H:i:s'),
				];
			}
			$date = Db::table('productpic')->insertAll($img_insert);
		}
		return $date;
	}

	/**
	 * 2018-05-30
	 * czw
	 * 编辑商品图片
	 */

	public function edit_product_image($product_id = 0, $where = array(), $image = array()) {
		$img_insert = array();
		$qiniuConfig = Config::get('qiniu');
		if (!$product_id || !$image[0] || !$where) {
			$date = array('code' => 20103, 'msg' => '添加图片的产品id，和要更新的图片不能为空', 'data' => '');
			exit(json_encode($date));
		} else {
			foreach ($image as $val) {
				if (strstr($val, 'http:')) {
					$pic_url = $val;
					$thumb_url = $val . $qiniuConfig['thumbnail'];
				} else {
					$pic_url = $qiniuConfig['domainName'] . $val;
					$thumb_url = $qiniuConfig['domainName'] . $val . $qiniuConfig['thumbnail'];
				}
				$img_insert[] = [
					'product_id' => $product_id,
					'pic_url' => $pic_url,
					'thumb_url' => $thumb_url,
					'createtime' => date('Y-m-d H:i:s'),
				];
			}
			try {
				$row = Db::table('productpic')->where($where)->setField('state', 1);
				$date = Db::table('productpic')->insertAll($img_insert);
				Db::commit();
			} catch (Exception $exc) {
				Db::rollback();
			}
		}
		return $date;
	}

	/**
	 * 规格属性组合
	 * @param type $systematics_arr
	 * @return type
	 */
	public function standard_attr($systematics_arr) {
		$standard_id = array();
		$date = array();
		$attr = array();
		$attr_arr = array();
		$standard = array();
		if (is_array($systematics_arr)) {
			if (array_key_exists('standard', $systematics_arr) && !empty($systematics_arr['standard'])) {
				foreach ($systematics_arr['standard'] as $k_s => $v_s) {
					$standard_id[] = $v_s['stid'];
					$standard = implode('-', $standard_id);
					if (array_key_exists('attr', $v_s)) {
						foreach ($v_s['attr'] as $k_a => $v_a) {
							$attr['title'] = $v_a;
							$attr['standard_id'] = $v_s['stid'];
							$attr_arr[] = $attr;
						}
					}
				}
			} else {
				$standard = $systematics_arr['standard'];
			}
		} else {
			$date = array('code' => 20066, 'msg' => '类目传参错误', 'data' => '');
		}
		if ($standard && $attr_arr) {
			$date['standard'] = $standard;
			$date['attr'] = $attr_arr;
		} else {
			$date['standard'] = $standard;
		}
		return $date;
	}

	/**
	 * 2018-4-10 日期格式
	 * 曹振威 开发人
	 * 产品删除
	 */
	public function operat_product() {
		$user_id = $this->user_id;
		$system_id = $this->system_id;
		$id = input('id');
		$type = input('type'); // 1:下架；2：删除；
		if (empty($id) || empty($type)) {
			$this->check_date = 1;
			$date = array('code' => 20021, 'msg' => '非法操作', 'data' => '');
		}
		if ($this->check_date != 0) {
			exit(json_encode($date));
		}

		$product = Db::table('product')->where(['id' => $id, 'state' => 0])->find();

		if (empty($product)) {
			$date = array('code' => 20067, 'msg' => '不存在该产品', 'data' => '');
			exit(json_encode($date));
		}

		$product_info = $this->product_info($id);
		Db::startTrans(); //开启事务
		try {
			$order = Db::table('orders_info')->where(['product_id' => $id, 'state' => 0])->find();
			if ($order != null && $order['status'] != 7) {
				$date = array('code' => 22220, 'msg' => '该商品已存在订单，不可删除商品', 'data' => '');
				exit(json_encode($date));
			}
			if ($product['is_synchro'] == 1) {
				//非自有商品，直接删除
				Db::table("product")
					->where(['id' => $id])
					->update(['state' => 1, 'updatetime' => date('Y-m-d H:i:s')]);
			} else {
				// 自有商品，删除自己的商品
				Db::table("product")
					->where(['id' => $id])
					->update(['state' => 1, 'updatetime' => date('Y-m-d H:i:s')]);
				//同时下架同步的所有商品
				Db::table("product")
					->where(['source_product_id' => $id])
					->update(['is_onsale' => 0, 'is_sold_business' => 1, 'updatetime' => date('Y-m-d H:i:s')]);
			}
			Db::table("productpic")->where('product_id', $id)->update(['state' => 1]); //商品图片
			Db::table("standard")->where('product_id', $id)->update(['state' => 1]); //商品规格

			// 提交事务
			Db::commit();

			$date = array('code' => 666, 'msg' => '商品删除成功', 'data' => '');

			OL::insert([
				'user_id' => $this->user_id,
				'module' => 'product',
				'module_id' => $id,
				'operation_type' => 4,
				'operation_content' => json_encode([
					'product' => Db::table('product')->where(['id' => $id])->find(),
				]),
			]);

		} catch (Exception $e) {
			// 回滚事务
			Db::rollback();
			$date = array('code' => 20048, 'msg' => '商品删除失败' . $e->getMessage(), 'data' => '');
		}

		if ($date['code'] == 666) {

			// 创建消息通知
			$description = $product_info['data']['full_name'];
			OrderService::notice_add($this->user_id, 5, 1, $this->business_id, $id, $description, 1, 0);
		}

		return $date;
	}

	/**
	 * 2018-4-11 日期格式
	 * 曹振威 开发人
	 * 产品列表
	 */
	public function product_list($action = '') {
		//产品状态   仓库中  已售完  出售中
		$whereor = array();
		$subsql = '';
		$page_current = input('page', 1);
		$reset = input('reset');
		$where = [
			'p.state' => 0,
			'p.business_id' => $this->business_id,
			'p.system_id' => $this->system_id,
//            'p.stock' => ['GT',0]
		];
		$is_synchr = input('is_synchro');
		if ($is_synchr == 1) {
			$is_synchro = [0];
		} elseif ($is_synchr == 2) {
			$is_synchro = [1];
		} else {
			$is_synchro = [0, 1];
		}
		$where['p.is_synchro'] = array('in', $is_synchro);
		$value_frist = input('value_frist');
		$brand = input('brand');
		if (!empty($brand)) {
			$where['p.category_id'] = $brand;
		}

		$long = input('long');
		if (isset($long) && $long != '') {
			if (input('long') == 1) {
				$order = ['p.createtine' => 'desc'];
			} elseif (input('long') == 0) {
				$order = ['p.createtine' => 'asc'];
			}
		} else {
			$order = ['p.id' => 'desc'];
		}
		input('procurement_status') ? $where['p.procurement_status'] = input('procurement_status') : FALSE;
		input('is_shelf') ? $where['p.is_shelf'] = input('is_shelf') : FALSE;
		input('store') ? $where['p.store_id'] = input('store') : FALSE;
		input('staff') ? $where['p.staff_id'] = input('staff') : FALSE;
		if (!empty(input('is_onsale'))) {
			if (input('is_onsale') == 2) {
				$where['p.is_onsale'] = 0; //查询下架
			} elseif (input('is_onsale') == 1) {
				$where['p.is_onsale'] = 1;
			}
		}
		$begin_time = input('begin_time');
		$end_time = input('end_time');
		if ($begin_time && empty($end_time)) {
			$where['p.createtine'] = ['EGT', $begin_time];
		} elseif (empty($begin_time) && $end_time) {
			$where['p.createtine'] = ['ELT', date('Y-m-d', strtotime("$end_time +1 day"))];
		} elseif ($begin_time && $end_time) {
			$end_time = date('Y-m-d', strtotime("$end_time +1 day"));
			$where['p.createtine'] = ['between', "$begin_time,$end_time"];
		}
		$price_name = input('price_name', 0);
		$begin_price = input('begin_price');
		$end_price = input('end_price');
		if ($price_name == 0) {
			$price_name_select = 'price';
		} elseif ($price_name == 1) {
			$price_name_select = 'cost_price';
		} elseif ($price_name == 2) {
			$price_name_select = 'peer_price';
		}
		if ($begin_price && empty($end_price)) {
			$where['p.' . $price_name_select] = ['EGT', "$begin_price"];
		} elseif (empty($begin_price) && $end_price) {
			$where['p.' . $price_name_select] = ['ELT', "$end_price"];
		} elseif ($begin_price && $end_price) {
			$where['p.' . $price_name_select] = ['between', "$begin_price,$end_price"];
		}
		if ($value_frist) {
			$whereor['p.full_name|p.product_sn|p.product_source|p.coordinate'] = ['like', "%" . input('value_frist') . "%"];
			$subsql = Db::table('attributevalue')
				->where(array('title' => ['like', "%" . input('value_frist') . "%"]))
				->group('product_id')->column('product_id');
		} else {
			$subsql = Db::table('product')->alias('p')->where($where)->column('id');
		}
		if ($reset == 1) {
			$where = [
				'p.state' => 0,
				'p.business_id' => $this->business_id,
				'p.system_id' => $this->system_id,
				//            'p.stock' => ['GT',0]
			];
			$whereor = array();
			$subsql = '';
		}
		$field = 'p.id,p.source_product_id,p.product_condition,pf.value product_condition_value,p.pic_url,p.thumb_url,p.stock,p.product_name,p.product_sn,'
			. 's.store_name,p.is_shelf,p.is_network, wc.value shelf_value,po.shares,po.views,p.procurement_status,ps.value procurement_value,p.cost_price,'
			. 'p.is_offsale,p.re_network,p.additional,st.name,p.product_source,p.createtine,p.peer_price,p.price,p.library_age,p.coordinate,p.is_synchro,p.is_sold_business,'
			. 'b.business_name,bs.business_name raw_business_name,se.store_name raw_store_name,pt.is_onsale source_is_onsale,pt.is_network source_is_network,p.is_onsale,p.systematics_id,p.product_state,pst.value product_state_value,p.brand_id,p.type_id,p.category_id';

		if (empty($action)) {
			$product_list = Db::table('product')->alias('p')
				->join('store s', 'p.store_id=s.id', 'LEFT')
				->join('product_other po', 'p.id=po.product_id', 'LEFT')
				->join('staff st', 'st.user_id=p.staff_id', 'LEFT')
				->join('business b', 'p.business_id = b.business_id', 'LEFT')
				->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
				->join('warehouse_condition wc', 'p.is_shelf = wc.id', 'LEFT')
				->join('perchase_source ps', 'p.procurement_status = ps.id', 'LEFT')
				->join('product_state pst', 'pst.id = p.product_state', 'LEFT')
				->join('product pt', 'p.source_product_id = pt.id', 'LEFT')
				->join('business bs', 'pt.business_id = bs.business_id', 'LEFT')
				->join('store se', 'pt.store_id = se.user_id', 'LEFT')
				->distinct(true)
				->where($where)->where(function ($obj) use ($whereor, $subsql) {
				$obj->whereor($whereor)->whereor('p.id', 'in', $subsql);
			})
				->order($order)
				->field($field)
				->select();
			// ->paginate()
			// ->toArray();
			foreach ($product_list as $key => $value) {
				$product_list[$key]['is_others'] = 0;
			}
			//$product_synchro = $this->getSynchroProducts($where,$order);
			//$product_list['total'] = $product_list['total']+count($product_synchro);
			// $product_list = array_merge($product_synchro,$product_list);

			foreach ($product_list as $pkey => $pvalue) {
				if ($pvalue['systematics_id']) {
					$systematics_arr = $this->set_product_name($pvalue['systematics_id']);
				} elseif ($pvalue['brand_id']) {
					$systematics_arr = $this->set_product_name($pvalue['brand_id']);
				} else {
					$systematics_arr = [];
				}

				if (!array_key_exists('data', $systematics_arr)) {
					$product_list[$pkey]['pre_name'] = '';
				} else {
					$product_list[$pkey]['pre_name'] = $systematics_arr['data'];
				}
				$library_time = $this->get_library_time($pvalue['createtine']);
				$product_list[$pkey]['library_time'] = $library_time;
			}
			foreach ($product_list as $key => $product) {
				if ($product['thumb_url'] == null) {
					$product_list[$key]['thumb_url'] = $product['pic_url'];
				}
				if($product['is_onsale']==0){
					$product_list[$key]['is_onsale']=2;
				}
				if($product['is_network']==0){
					$product_list[$key]['is_network']=2;
				}
			}
			if (null != input('product_state')) {
				foreach ($product_list as $key => $product) {
					if (input('product_state') == 1) {
						$product_list = array_filter($product_list, function ($p) {return in_array($p['product_state'], [1, 2, 3, 4]);});
					} elseif (input('product_state') == 2) {
						$product_list = array_filter($product_list, function ($p) {return in_array($p['product_state'], [5, 6, 7, 8]);});
					} elseif (input('product_state') == 3) {
						$product_list = array_filter($product_list, function ($p) {return in_array($p['product_state'], [9, 10, 11, 12]);});
					} elseif (input('product_state') == 4) {
						$product_list = array_filter($product_list, function ($p) {return in_array($p['product_state'], [13]);});
					} elseif (input('product_state') == 5) {
						$product_list = array_filter($product_list, function ($p) {return in_array($p['product_state'], [14]);});
					} elseif (input('product_state') == 6) {
						$product_list = array_filter($product_list, function ($p) {return in_array($p['product_state'], [15]);});
					}
				}
			}

			$date = array('code' => 666, 'msg' => '产品列表获取成功', 'data' => ['data' => array_slice($product_list, ($page_current - 1) * 20, 20), 'total' => count($product_list), 'per_page' => 20, 'current_page' => $page_current]);
			IL::insert('log', [
				'user_id' => $this->user_id,
				'operation_user' => $this->user['name'],
				'operation_name' => '查看',
				'operation_content' => '查看产品列表',
				'operation_type' => 1,
				'ip' => Request()->ip(),
				'createtime' => date('Y-m-d H:i:s'),
				'state' => 1,
			]);

		} elseif ($action == 'product_excel') {
			$date = Db::table('product')->alias('p')
				->join('store s', 'p.store_id=s.user_id', 'LEFT')
				->join('product_other po', 'p.id=po.product_id', 'LEFT')
				->join('staff st', 'st.user_id=p.staff_id', 'LEFT')
				->join('business b', 'p.business_id = b.business_id', 'LEFT')
				->where($where)->where(function ($obj) use ($whereor, $subsql) {
				$obj->whereor($whereor)->whereor('p.id', 'in', $subsql);
			})
				->order($order)
				->field($field)
				->select();
		}
		if (input('value_frist')) {
			$user_id = $this->user_id;
			Helptype::search_keyword(input('value_frist'), $user_id);

		}
		return $date;
	}

	// public function getSynchroProducts($where,$order)
	// {
	//     $where['psy.user_id'] = $this->business_id;
	//     $where['psy.state'] = 0;
	//     unset($where['p.business_id']);
	//     $fieldSynchro = 'p.id,p.product_condition,pf.value product_condition_value, p.pic_url, p.thumb_url, p.stock, p.product_name, p.product_sn,'
	//         . 'p.is_shelf, p.is_network,wc.value shelf_value, po.shares, po.views,p.procurement_status,ps.value procurement_value,p.createtine,'
	//         . 'p.additional,p.peer_price,psy.price, psy.synopsis, psy.is_autodeliver, psy.delivery_id, dy.province, dy.city, dy.district, dy.address, dy.name delivery_name, dy.phone delivery_phone ,'
	//         . 'b.business_name,p.is_onsale,p.systematics_id,p.product_state,pst.value product_state_value,p.brand_id,p.type_id,p.category_id';
	//     $product_synchro = Db::table('product_synchro')->alias('psy')
	//                         ->join('product p','psy.product_id = p.id','LEFT')
	//                         ->join('store s','p.store_id=s.user_id','LEFT')
	//                         ->join('product_other po','p.id=po.product_id','LEFT')
	//                         ->join('staff st','st.user_id=p.staff_id','LEFT')
	//                         ->join('business b','p.business_id = b.business_id','LEFT')
	//                         ->join('product_fineness pf','p.product_condition = pf.id', 'LEFT')
	//                         ->join('warehouse_condition wc','p.is_shelf = wc.id', 'LEFT')
	//                         ->join('perchase_source ps','p.procurement_status = ps.id', 'LEFT')
	//                         ->join('product_state pst','pst.id = p.product_state','LEFT')
	//                         ->join('delivery dy','dy.id = psy.delivery_id','LEFT')
	//                         ->where($where)
	//                         ->order($order)
	//                         ->field($fieldSynchro)
	//                         ->select();
	//     foreach ($product_synchro as $key => $p) {
	//         $product_synchro[$key]['is_others'] =  1;
	//     }
	//     return $product_synchro;
	// }

	public function getBrandIds($brand_id) {
		if ($brand_id < 5) {
			$brands = DB::table('systematics')
				->where(['id' => $brand_id])
				->whereor(['superior_id' => $brand_id])
				->whereor(['superior_gene' => ['like', $brand_id . "-%"]])
				->field('id')
				->select();
		} elseif ($brand_id > 4 && $brand_id < 42) {
			$brands = DB::table('systematics')
				->where(['id' => $brand_id])
				->whereor(['superior_id' => $brand_id])
				->whereor(['superior_gene' => ['like', "%-" . $brand_id]])
				->whereor(['superior_gene' => ['like', "%-" . $brand_id . "-%"]])
				->field('id')
				->select();
		} elseif ($brand_id > 41 && $brand_id < 2686) {
			$brands = DB::table('systematics')
				->where(['id' => $brand_id])
				->whereor(['superior_id' => $brand_id])
				->whereor(['superior_gene' => ['like', "%-" . $brand_id]])
				->field('id')
				->select();
		} else {
			$brands = DB::table('systematics')
				->where(['id' => $brand_id])
				->field('id')
				->select();
		}

		$brand_ids = [];
		foreach ($brands as $brand) {
			$brand_ids[] = $brand['id'];
		}
		return $brand_ids;
	}

	/**
	 * 2018-4-12 日期格式
	 * 曹振威 开发人
	 * 产品信息详情
	 */
	public function product_info($id = 0) {
		if (!$id) {
			$date = array('code' => 20202, 'msg' => '获取商品详情的产品编号不能为空', 'data' => '');
			exit(json_encode($date));
		}
		$this->check_product($id);
		$where['p.id'] = $id;
		$where['p.state'] = 0;
		$where['p.system_id'] = $this->system_id;
		$where['p.business_id'] = $this->business_id;
		$where_img = [
			'state' => 0,
		];
		$field = 'p.id,p.is_shelf,p.product_name,pf.value product_condition_value,p.product_cate,p.product_condition,p.business_id,'
			. 'p.procurement_status,p.price,wc.value shelf_value,p.peer_price,p.product_sn,p.createtine,ps.value procurement_value,'
			. 'p.product_code,p.cost_price,p.synopsis,p.category_id,p.type_id,p.brand_id,p.systematics_id,p.stock,p.full_name,'
			. 'p.maintenance,p.coordinate,p.library_age,p.remark,p.additional,'
			. 'p.product_source,p.staff_id sale_id,st.user_id staff_id,st.name staff_name,p.origin_id,p.receive_share,p.sale_share,'
			. 's.user_id store_id,s.store_name,p.pic_url,p.is_onsale,p.is_network,p.product_state,pst.value product_state_value,p.brand_id,p.type_id,'
			. 'p.category_id';
		$product_info = Db::table('product')->alias('p')
			->join('staff st', 'p.staff_id = st.user_id', 'LEFT')
			->join('store s', 'p.store_id = s.user_id', 'LEFT')
			->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
			->join('warehouse_condition wc', 'p.is_shelf = wc.id', 'LEFT')
			->join('perchase_source ps', 'p.procurement_status = ps.id', 'LEFT')
			->join('product_state pst', 'pst.id = p.product_state', 'LEFT')
			->where($where)->field($field)->find();
		if (!$product_info['staff_id']) {
			// 采购员是商户或门店
			$row = Db::table('users')->where('id', $product_info['sale_id'])->field('id,name')->find();
			$product_info['staff_id'] = $row['id'];
			$product_info['staff_name'] = $row['name'];
		}
		if($product_info['is_onsale']==0){
			$product_info['is_onsale']=2;
		}
		if($product_info['is_network']==0){
			$product_info['is_network']=2;
		}
		if (!$product_info['store_id']) {
			// 商品所属商铺
			$row_business = Db::table('business')->where('business_id', $product_info['business_id'])->field('business_id,business_name')->find();
			$product_info['store_id'] = $row_business['business_id'];
			$product_info['store_name'] = $row_business['business_name'];
		}
		if ($product_info['systematics_id']) {
			$systematics_arr = $this->set_product_name($product_info['systematics_id']);
			$product_systematics = $this->get_systematics($product_info['systematics_id']);
		} elseif ($product_info['brand_id']) {
			$systematics_arr = $this->set_product_name($product_info['brand_id']);
			$product_systematics = $this->get_systematics($product_info['brand_id']);
		} elseif ($product_info['type_id']) {
			$systematics_arr = $this->set_product_name($product_info['type_id']);
			$product_systematics = $this->get_systematics($product_info['type_id']);
		} elseif ($product_info['category_id']) {
			$systematics_arr = $this->set_product_name($product_info['category_id']);
			$product_systematics = $this->get_systematics($product_info['category_id']);
		} else {
			$systematics_arr = [];
			$product_systematics = [];
		}
		if (!array_key_exists('data', $systematics_arr)) {
			$product_info['pre_name'] = '';
		} else {
			$product_info['pre_name'] = $systematics_arr['data'];
		}
		$product_img = $this->get_img($id, $where_img);
		$product_standard = $this->get_standard($id);
		$product_info['systematics_info'] = $product_systematics;
		$product_info['systematics_info']['standard'] = $product_standard;
		$product_info['image'] = $product_img;
		if ($product_info) {
			if ($product_info['systematics_id'] == null && $product_info['brand_id'] != null) {
				$product_info['systematics_id'] = $product_info['brand_id'];
			} elseif ($product_info['systematics_id'] == null && $product_info['brand_id'] == null && $product_info['type_id'] != null) {
				$product_info['systematics_id'] = $product_info['type_id'];
			} elseif ($product_info['systematics_id'] == null && $product_info['brand_id'] == null && $product_info['type_id'] == null && $product_info['category_id'] != null) {
				$product_info['systematics_id'] = $product_info['category_id'];
			}
			$date = array('code' => 666, 'msg' => '产品信息获取成功', 'data' => $product_info);
			IL::insert('log', [
				'user_id' => $this->user_id,
				'operation_user' => $this->user['name'],
				'product_id' => $id,
				'operation_type' => 1,
				'operation_name' => '查看',
				'operation_content' => '查看产品详情',
				'ip' => Request()->ip(),
				'createtime' => date('Y-m-d H:i:s'),
				'state' => 1,
			]);
		} else {
			$date = array('code' => 20028, 'msg' => '产品信息获取失败', 'data' => '');
			IL::insert('log', [
				'user_id' => $this->user_id,
				'operation_user' => $this->user['name'],
				'product_id' => $id,
				'operation_type' => 1,
				'operation_name' => '查看',
				'operation_content' => '查看产品详情',
				'ip' => Request()->ip(),
				'createtime' => date('Y-m-d H:i:s'),
				'state' => 0,
			]);
		}
		return $date;
	}

	public function get_img($product_id, $where = '') {
		if ($product_id) {
			$where['product_id'] = $product_id;
			$where['state'] = 0;
			$date = Db::table('productpic')->where($where)->field('id,product_id,pic_url')->select();
		} else {
			$date = array('code' => 20071, 'msg' => '获取图片的产品id不能为空', 'data' => '');
		}
		return $date;
	}

	public function get_standard($product_id, $where = array()) {
		$date = array();
		if ($product_id) {
			$where['id'] = $product_id;
			$where['state'] = 0;
			$standar_id = Db::table('product')->where($where)->value('standard_id');
			if ($standar_id) {
				$standar_arr = explode('-', $standar_id);
				foreach ($standar_arr as $key => $value) {
					$row_standard = Db::table('standard')->where('id', $value)->field('id,title')->find();
					$row_attr = $this->get_attr($product_id, $value);
					$date[$key] = $row_standard;
					$date[$key]['attr'] = $row_attr;
				}
			}
		} else {
			$date = array('code' => 20072, 'msg' => '获取规格的产品id不能为空', 'data' => '');
			exit(json_encode($date));
		}
		return $date;
	}

	public function get_attr($product_id, $standard_id) {
		$date = array();
		if ($standard_id && $product_id) {
			$where_attr = [
				'product_id' => $product_id,
				'standard_id' => $standard_id,
				'state' => 0,
			];
			$date = Db::table('attributevalue')->where($where_attr)->field('id,product_id,standard_id,title')->select();
		} else {
			$date = array('code' => 20082, 'msg' => '获取属性的产品id不能为空', 'data' => '');
			exit(json_encode($date));
		}
		return $date;
	}
	/**
	 * 2018-05-31
	 * czw 改
	 * @param type $systematics
	 * @return int
	 */
//     public function get_systematics($systematics){
	//         $date = array();
	//         if($systematics){
	//             $row = Db::table('systematics')->where('id',$systematics)->field('id,superior_id,superior_gene,title')->find();
	//             $superior_id = $row['superior_id'];
	//             $superior_gene = $row['superior_gene'];
	//             $superior_gene_arr = explode('-',$superior_gene);
	//             if($superior_gene){
	//                 foreach ($superior_gene_arr as $sk => $sv) {
	//                     $row_sy = Db::table('systematics')->where('id',$sv)->field('id,title')->find();
	//                     if($sk == 0){
	//                         $date['systematics'] = $row_sy;
	//                         $date['child_systematics']['id'] = $row['id'];
	//                         $date['child_systematics']['title'] = $row['title'];
	//                     }elseif ($sk == 1) {
	//                         $date['child_systematics'] = $row_sy;
	//                         $date['brand']['id'] = $row['id'];
	//                         $date['brand']['title'] = $row['title'];
	//                     }elseif($sk == 2){
	//                         $date['brand'] = $row_sy;
	//                         $date['xilie']['id'] = $row['id'];
	//                         $date['xilie']['title'] = $row['title'];
	//                     }elseif($sk == 3){
	//                         $date['xilie'] = $row_sy;
	//                     }
	//                 }
	//             }else{
	//                 $date['systematics'] = Db::table('systematics')->where('id',$systematics)->field('id,title')->find();
	//             }
	//         }else{
	//             $date = [];
	//         }
	//         return $date;
	//     }

	public function get_systematics($systematics) {
		$row = Db::table('systematics')->where('id', $systematics)->field('id,superior_id,superior_gene,title')->find();

		if ($row != null) {
			if ($row['superior_gene'] == 0) {
				$date['systematics']['id'] = (int) $systematics;
				$date['systematics']['title'] = $row['title'];
			} else {
				$superior_gene_arr = explode('-', $row['superior_gene']);
				if (count($superior_gene_arr) == 1) {
					$date['systematics']['id'] = (int) $row['superior_id'];
					$title = Db::table('systematics')->where('id', $row['superior_id'])->field('title')->find();
					$date['systematics']['title'] = $title['title'];

					$date['child_systematics']['id'] = (int) $systematics;
					$date['child_systematics']['title'] = $row['title'];
				} elseif (count($superior_gene_arr) == 2) {
					$date['systematics']['id'] = (int) $superior_gene_arr[0];
					$title = Db::table('systematics')->where('id', $superior_gene_arr[0])->field('title')->find();
					$date['systematics']['title'] = $title['title'];

					$date['child_systematics']['id'] = (int) $superior_gene_arr[1];
					$title = Db::table('systematics')->where('id', $superior_gene_arr[1])->field('title')->find();
					$date['child_systematics']['title'] = $title['title'];

					$date['brand']['id'] = (int) $systematics;
					$date['brand']['title'] = $row['title'];
				} elseif (count($superior_gene_arr) == 3) {
					$date['systematics']['id'] = (int) $superior_gene_arr[0];
					$title = Db::table('systematics')->where('id', $superior_gene_arr[0])->field('title')->find();
					$date['systematics']['title'] = $title['title'];

					$date['child_systematics']['id'] = (int) $superior_gene_arr[1];
					$title = Db::table('systematics')->where('id', $superior_gene_arr[1])->field('title')->find();
					$date['child_systematics']['title'] = $title['title'];

					$date['brand']['id'] = (int) $superior_gene_arr[2];
					$title = Db::table('systematics')->where('id', $superior_gene_arr[2])->field('title')->find();
					$date['brand']['title'] = $title['title'];

					$date['xilie']['id'] = (int) $systematics;
					$date['xilie']['title'] = $row['title'];
				}
			}

		} else {
			$date = [];
		}

		return $date;
	}

	public function match_shelf($id) {
		$D = new Dropdown();
		$warehouse_condition = $D->warehouse_condition();
		return $warehouse_condition['data'][$id - 1];
	}

	/**
	 * 2018-04-27 开发日期
	 * 曹振威 开发人
	 * 查看产品轨迹
	 * @return string
	 */
	public function select_product_route() {
		$id = input('id');
		if (!$id) {
			$date = array('code' => 20021, 'msg' => '查看商品轨迹的商品编号不能为空', 'data' => '');
			exit(json_encode($date));
		}
		$this->check_product($id);
		$where['p.system_id'] = $this->system_id;
		$where['p.business_id'] = $this->business_id;
		$where['p.id'] = $id;
		$where['p.state'] = 0;
		$field = 'p.id,p.is_shelf, wc.value shelf_value, p.product_sn,p.cost_price,'
			. 'p.peer_price,p.price,s.store_name,p.procurement_status, ps.value procurement_value';
		$route = Db::table('product')
			->alias('p')
			->join('store s', 'p.store_id=s.user_id', 'LEFT')
			->join('warehouse_condition wc', 'p.is_shelf=wc.id', 'LEFT')
			->join('perchase_source ps', 'p.procurement_status=ps.id', 'LEFT')
			->where($where)->field($field)
			->find();
		$log_field = 'u.name,op.operation_content,op.operation_time';
		$log = Db::table('operation_log')->alias('op')
			->join('users u', 'u.id=op.user_id', 'LEFT')
			->where(array('op.module' => 'product', 'module_id' => $id))
			->field($log_field)
			->order('op.id desc')
			->select();
		if (!$log) {
			$ol_log = [];
		} else {
			foreach ($log as $lkey => $lvalue) {
				$new = json_decode($lvalue['operation_content'], true);
				$ol_log[] = $new['product'];
			}
		}
		$operation_content = [];
		$a = [];
		if ($ol_log) {
			$i = 0;
			foreach ($ol_log as $olk => $olv) {
				if ($olv) {
					$arr_new = $this->check_log($olv);
					if (!empty($arr_new)) {
						$arr = $this->match_shelf($arr_new['is_shelf']);
						$operation_content[$i]['operation_content'] = $arr;
						$operation_content[$i]['operation_user'] = $log[$olk]['name'];
						$operation_content[$i]['createtime'] = $log[$olk]['operation_time'];
						$i++;
					}
				}
			}
		}
		$route['route'] = $operation_content;
		$date = array('code' => 666, 'msg' => '产品轨迹获取成功', 'data' => $route);
		return $date;
	}

	public function check_log($array = array()) {
		$arr_new = [];
		$arr = array('is_shelf' => '');
		foreach ($array as $ak => $av) {
			if (array_key_exists("$ak", $arr)) {
				$arr_new = [$ak => $av];
			}
		}
		return $arr_new;
	}
	/**
	 * 2018-04-28
	 * 曹振威
	 * 产品上架
	 * @return string
	 */
	public function product_onsale() {
		$where = array();
		$id = input('id');
		if ($this->business_id) {
			$where['business_id'] = $this->business_id;
		}
		if ($id) {
			$product_ids = explode(",", $id);
			$product = Db::table('product')->where(array('business_id' => $this->business_id, 'id' => ['IN', $product_ids], 'state' => 0))->find();
			if (!$product) {
				$date = array('code' => 20067, 'msg' => '不存在该产品', 'data' => '');
				exit(json_encode($date));
			}
			$row = Db::table('product')->where($where)->whereIn('id', $product_ids)->setField('is_shelf', 2);
			if ($row) {
				$date = array('code' => 666, 'msg' => '产品上架成功', 'data' => '');
				foreach ($product_ids as $key => $value) {
					OL::insert([
						'user_id' => $this->user_id,
						'module' => 'product',
						'module_id' => $value,
						'operation_type' => 4,
						'operation_content' => json_encode([
							'product' => Db::table('product')->where(['id' => $value])->find(),
						]),
					]);
				}
			} else {
				$date = array('code' => 20062, 'msg' => '产品上架失败', 'data' => '');
			}
		} else {
			$date = array('code' => 20021, 'msg' => '非法操作', 'data' => '');
		}
		return $date;
	}

	/**
	 * 2018-04-20
	 * 曹振威
	 * 产品列表导出
	 */
	public function product_excel() {
		$data = $this->product_list('product_excel');
		$key = [
			'产品编号', '产品名称', '产品图片', '产品现价', '成本价', '同行价', '产品数量',
		];
		$keyname = array('id', 'product_name', 'pic_url', 'price', 'cost_price', 'peer_price', 'stock');
		$styleArray = [
			'font' => ['bold' => true],
		];
		common::output_excel($key, $data, $keyname, '产品列表', $styleArray);
	}

	/**
	 * 返回库存状态
	 * @param type $product_id
	 */
	public function get_stock_status($product_id = '', $num = 0) {
		$i = 0;
		if (!$product_id) {
			$i = 1;
			$date = array('code' => 20084, 'msg' => '获取库存的产品id不能为空', 'data' => '');
		} else {
			$stock = Db::table('product')->where('id', $product_id)->value('stock');
			if (!$stock || $stock <= 0) {
				$row = Db::table('product')->where('id', $product_id)->setField('is_onsale', 1);
				$i = 1;
				$date = array('code' => 20085, 'msg' => '库存为空', 'data' => '');
			} elseif ($stock < $num) {
				$i = 1;
				$date = array('code' => 20086, 'msg' => '库存太少了，买的太多了', 'data' => '');
			}
		}
		if ($i == 1) {
			exit(json_encode($date));
		}
	}

	/**
	 * 2018-06-01
	 * czw
	 * 验证产品是否存在
	 * @param type $product_id
	 */
	public function check_product($product_id = 0) {
		$product_info = Db::table('product')->where(array('business_id' => $this->business_id, 'id' => $product_id, 'state' => 0))->find();
		if (!$product_info) {
			$date = array('code' => 20067, 'msg' => '不存在该产品', 'data' => '');
			exit(json_encode($date));
		}
		return $product_info;
	}

	/**
	 * 2018-07-01  改
	 * 2018-06-05
	 * czw
	 * 验证商品商品状态是否可以售出
	 */
	public function check_shelf($product_id = 0) {
		if (!$product_id) {
			$date = array('code' => 29993, 'msg' => '检验库存状态的产品编号不能为空', 'data' => '');
		} else {
			$product_info = $this->check_product($product_id);
			$order = Db::table('orders_info')->where(array('product_id' => $product_id, 'is_nursing' => 0, 'status' => ['NEQ', 7], 'state' => 0))->select();
			if (!in_array($product_info['product_state'], array('1', '2', '3', '4', '15'))) {
				$date = array('code' => 29997, 'msg' => '该商品状态不能售出', 'data' => '');
			} elseif ($product_info['is_own'] == 1) {
				$date = array('code' => 29997, 'msg' => '非自有商品，不能售出', 'data' => '');
			} elseif ($order) {
				$date = array('code' => 29997, 'msg' => '该商品的已存在售出订单', 'data' => '');
			} else {
				$date = array('code' => 666, 'msg' => '该商品的库存状态可以售出', 'data' => '');
			}
		}
		return $date;
	}

	public function insert_user_customer($product_source, $staff_id) {
		$user_insert = [
			'system_id' => $this->system_id,
			'business_id' => $this->business_id,
//            'store_id' => $this->store_id,
			'phone' => $product_source,
			'createtime' => date('Y-m-d H:i:s'),
			'is_customer' => 1,
		];
		$customer = Db::table('users')->insertGetId($user_insert);
		$customer_insert = [
			'system_id' => $this->system_id,
			'business_id' => $this->business_id,
			'store_id' => $this->store_id,
			'sales_id' => $staff_id,
			'user_id' => $customer,
			'createtime' => date('Y-m-d H:i:s'),
		];
		Db::table('customer')->insert($customer_insert);
		return $customer;
	}

	public function get_library_time($createtine) {
		$second1 = strtotime(date('Y-m-d H:i:s'));
		$second2 = strtotime($createtine);
		if ($second1 < $second2) {
			$tmp = $second2;
			$second2 = $second1;
			$second1 = $tmp;
		}
		return intval(($second1 - $second2) / 86400);
	}

	/**
	 * 2018-07-01
	 * czw
	 * 库存状态对应商品情况
	 */
	public function warehouse_product($warehouse_condition) {
		switch ($warehouse_condition) {
		case '1':
			return 2;
			break;

		case '2':
			return 1;
			break;

		case '3':
			return 4;
			break;

		default:
			return 0;
			break;
		}
	}

	/**
	 * @Notes:非自有商品编辑
	 * @param Request $request
	 * @return array
	 * @author: LiBaoJin
	 * @Time:
	 */
	public function is_synchro_selsct_by_id(Request $request) {
		$postData = $request->post();
		$reData = ['code' => 666, 'msg' => '', 'data' => []];
		if (empty($postData)) {
			$reData['code'] = -1;
			$reData['msg'] = '请选择需要编辑的商品';
			return $reData;
		}
		try {
			$product_data = Db::table('product')
				->alias('p')
				->where(['p.id' => $postData['id'], 'p.state' => 0])
				->field('p.id,p.business_id,p.is_network,p.full_name,p.is_onsale,p.product_name,p.peer_price,p.product_condition,p.stock,p.is_autodeliver,p.delivery_id,p.synopsis,p.remark,p.is_synchro,p.price')
				->find();
			if ($product_data['is_autodeliver'] == 0) {
				$product_data['is_autodeliver'] = 2;
			}
			$product_img = Db::table('productpic')
				->where(['product_id' => $product_data['id'], 'state' => 0])
				->field('id,pic_url')
				->select();
			$product_condition = Db::table('product_fineness')
				->where(['id' => $product_data['product_condition'], 'state' => 0])
				->field('value')
				->find();
			if ($product_data['is_autodeliver'] == 1) {
				$delivery_id = Db::table('delivery')
					->where(['id' => $product_data['delivery_id'], 'state' => 0])
					->find();
				$product_data['delivery_id'] = $delivery_id;
			} else {
				$product_data['delivery_id'] = [];
			}

			$product_data['condition'] = $product_condition['value'];
			$product_data['img'] = $product_img;
			$user_data = Db::table('users')
				->where(['id' => $this->user_id, 'state' => 0])
				->field('business_id,is_staff,id,is_business')
				->find();
			if ($user_data['is_business'] == 1 || $user_data['is_business'] == 2) {
				$product_info = Db::table('merchant')
					->where(['user_id' => $user_data['id'], 'state' => 0])
					->field('merContactPhone,merShortName')
					->find();
			} elseif ($user_data['is_staff'] == 1) {
				$product_info = Db::table('staff')
					->alias('s')
					->join('merchant m', 's.business_id = m.user_id', 'LEFT')
					->where(['s.user_id' => $this->user_id, 's.state' => 0])
					->field('m.merContactPhone,m.merShortName')
					->find();
			}
			if (isset($product_info)) {
				$product_data['product_info'] = $product_info;
			}
			$reData['data'][] = $product_data;
			return $reData;

		} catch (Exception $e) {
			$reData['code'] = -1;
			$reData['msg'] = $e->getMessage();
			return $reData;
		}

	}

	/**非自有商品编辑
		     * @Notes:
		     * @param Request $request
		     * @return array
		     * @author: LiBaoJin
		     * @Time:
	*/
	public function is_synchro_updata(Request $request) {
		$postData = $request->post();
		$reData = ['code' => 666, 'msg' => '', 'data' => []];
		$rules = [
			'id' => 'require',
			'price' => 'require',
			'synopsis' => 'require',
			'is_autodeliver' => 'require',

		];

		$msg = [
			'price.require' => '请填写销售价',
			'is_autodeliver.require' => '是否代发货不能为空',
			'synosis.require' => '请填写商品描述',

		];
		$rule = $this->validate($postData, $rules, $msg);
		if ($rule !== true) {
			$reData['code'] = -1;
			$reData['msg'] = $rule;
			return $reData;
		}
		try {
			$ture_data = Db::table('product')
				->where(['id' => $postData['id']])
				->field('peer_price,id')
				->find();

			if ($ture_data['peer_price'] > $postData['price']) {
				$reData['code'] = -1;
				$reData['msg'] = '销售价不能低于同行价';
				return $reData;
			}
			if ($postData['is_autodeliver'] == 1) {
				if (empty($postData['name'])) {
					$back['code'] = -1;
					$back['msg'] = '姓名不能为空';
					return $back;
				} elseif (empty($postData['province'])) {
					$back['code'] = -1;
					$back['msg'] = '省份不能为空';
					return $back;
				} elseif (empty($postData['city'])) {
					$back['code'] = -1;
					$back['msg'] = '市不能为空';
					return $back;
				} elseif (empty($postData['district'])) {
					$back['code'] = -1;
					$back['msg'] = '地区不能为空';
					return $back;
				} elseif (empty($postData['address'])) {
					$back['code'] = -1;
					$back['msg'] = '详细地址不能为空';
					return $back;
				} elseif (empty($postData['phone'])) {
					$back['code'] = -1;
					$back['msg'] = '电话不能为空';
					return $back;
				}

				$delivery_id = Db::table('delivery')
					->insertGetId([
						'user_id' => $this->user_id,
						'province' => $postData['province'],
						'city' => $postData['city'],
						'district' => $postData['district'],
						'address' => $postData['address'],
						'phone' => $postData['phone'],
						'name' => $postData['name'],
						'is_default' => 0,
						'state' => 0,
						'create_time' => date('Y-m-d H:i:s', time()),
						'update_time' => date('Y-m-d H:i:s', time()),
					]);
				Db::table('product')
					->where(['id' => $postData['id']])
					->update([
						'is_autodeliver' => 1,
						'delivery_id' => $delivery_id,
						'synopsis' => $postData['synopsis'],
						'price' => $postData['price'],
						'updatetime' => date('Y-m-d H:i:s', time()),

					]);
			} else {
				Db::table('product')
					->where(['id' => $postData['id']])
					->update([
						'is_autodeliver' => 0,
						'synopsis' => $postData['synopsis'],
						'price' => $postData['price'],
						'updatetime' => date('Y-m-d H:i:s', time()),
					]);
			}
			return $reData;

		} catch (Exception $e) {
			$reData['code'] = -1;
			$reData['msg'] = $e->getMessage();
			return $reData;
		}
	}

	/**
	 * @Notes:banner商品列表获取
	 * @param string $action
	 * @return array|false|\PDOStatement|string|\think\Collection
	 * @author: LiBaoJin
	 * @Time:
	 */
	public function banner_list($action = '') {
		//产品状态   仓库中  已售完  出售中
		$whereor = array();
		$subsql = '';
		$page_current = input('page', 1);
		$reset = input('reset');
		$where = [
			'p.state' => 0,
			'p.business_id' => $this->business_id,
			'p.system_id' => $this->system_id,
			'p.is_onsale'=>1
		];
		$is_synchr = input('is_synchro');
		if ($is_synchr == 1) {
			$is_synchro = [0];
		} elseif ($is_synchr == 2) {
			$is_synchro = [1];
		} else {
			$is_synchro = [0, 1];
		}
		$where['p.is_synchro'] = array('in', $is_synchro);
		$value_frist = input('value_frist');
		$brand = input('brand');
		if (!empty($brand)) {
			$where['p.category_id'] = $brand;
		}

		$long = input('long');
		if (isset($long) && $long != '') {
			if (input('long') == 1) {
				$order = ['p.createtine' => 'desc'];
			} elseif (input('long') == 0) {
				$order = ['p.createtine' => 'asc'];
			}
		} else {
			$order = ['p.id' => 'desc'];
		}
		input('procurement_status') ? $where['p.procurement_status'] = input('procurement_status') : FALSE;
		input('is_shelf') ? $where['p.is_shelf'] = input('is_shelf') : FALSE;
		input('store') ? $where['p.store_id'] = input('store') : FALSE;
		input('staff') ? $where['p.staff_id'] = input('staff') : FALSE;
		$begin_time = input('begin_time');
		$end_time = input('end_time');
		if ($begin_time && empty($end_time)) {
			$where['p.createtine'] = ['EGT', $begin_time];
		} elseif (empty($begin_time) && $end_time) {
			$where['p.createtine'] = ['ELT', date('Y-m-d', strtotime("$end_time +1 day"))];
		} elseif ($begin_time && $end_time) {
			$end_time = date('Y-m-d', strtotime("$end_time +1 day"));
			$where['p.createtine'] = ['between', "$begin_time,$end_time"];
		}
		$price_name = input('price_name', 0);
		$begin_price = input('begin_price');
		$end_price = input('end_price');
		if ($price_name == 0) {
			$price_name_select = 'price';
		} elseif ($price_name == 1) {
			$price_name_select = 'cost_price';
		} elseif ($price_name == 2) {
			$price_name_select = 'peer_price';
		}
		if ($begin_price && empty($end_price)) {
			$where['p.' . $price_name_select] = ['EGT', "$begin_price"];
		} elseif (empty($begin_price) && $end_price) {
			$where['p.' . $price_name_select] = ['ELT', "$end_price"];
		} elseif ($begin_price && $end_price) {
			$where['p.' . $price_name_select] = ['between', "$begin_price,$end_price"];
		}
		if ($value_frist) {
			$whereor['p.full_name|p.product_sn|p.product_source|p.coordinate'] = ['like', "%" . input('value_frist') . "%"];
			$subsql = Db::table('attributevalue')
				->where(array('title' => ['like', "%" . input('value_frist') . "%"]))
				->group('product_id')->column('product_id');
		} else {
			$subsql = Db::table('product')->alias('p')->where($where)->column('id');
		}
		if ($reset == 1) {
			$where = [
				'p.state' => 0,
				'p.business_id' => $this->business_id,
				'p.system_id' => $this->system_id,
				'p.is_onsale'=>1
			];
			$whereor = array();
			$subsql = '';
		}
		$field = 'p.id,p.source_product_id,p.product_condition,pf.value product_condition_value,p.pic_url,p.thumb_url,p.stock,p.product_name,p.product_sn,'
			. 's.store_name,p.is_shelf,p.is_network, wc.value shelf_value,po.shares,po.views,p.procurement_status,ps.value procurement_value,p.cost_price,'
			. 'p.is_offsale,p.re_network,p.additional,st.name,p.product_source,p.createtine,p.peer_price,p.price,p.library_age,p.coordinate,p.is_synchro,p.is_sold_business,'
			. 'b.business_name,bs.business_name raw_business_name,se.store_name raw_store_name,pt.is_onsale source_is_onsale,pt.is_network source_is_network,p.is_onsale,p.systematics_id,p.product_state,pst.value product_state_value,p.brand_id,p.type_id,p.category_id';

		if (empty($action)) {
			$product_list = Db::table('product')->alias('p')
				->join('store s', 'p.store_id=s.id', 'LEFT')
				->join('product_other po', 'p.id=po.product_id', 'LEFT')
				->join('staff st', 'st.user_id=p.staff_id', 'LEFT')
				->join('business b', 'p.business_id = b.business_id', 'LEFT')
				->join('product_fineness pf', 'p.product_condition = pf.id', 'LEFT')
				->join('warehouse_condition wc', 'p.is_shelf = wc.id', 'LEFT')
				->join('perchase_source ps', 'p.procurement_status = ps.id', 'LEFT')
				->join('product_state pst', 'pst.id = p.product_state', 'LEFT')
				->join('product pt', 'p.source_product_id = pt.id', 'LEFT')
				->join('business bs', 'pt.business_id = bs.business_id', 'LEFT')
				->join('store se', 'pt.store_id = se.user_id', 'LEFT')
				->distinct(true)
				->where($where)->where(function ($obj) use ($whereor, $subsql) {
					$obj->whereor($whereor)->whereor('p.id', 'in', $subsql);
				})
				->order($order)
				->field($field)
				->select();
			foreach ($product_list as $key => $value) {
				$product_list[$key]['is_others'] = 0;
			}
			foreach ($product_list as $pkey => $pvalue) {
				if ($pvalue['systematics_id']) {
					$systematics_arr = $this->set_product_name($pvalue['systematics_id']);
				} elseif ($pvalue['brand_id']) {
					$systematics_arr = $this->set_product_name($pvalue['brand_id']);
				} else {
					$systematics_arr = [];
				}
				if (!array_key_exists('data', $systematics_arr)) {
					$product_list[$pkey]['pre_name'] = '';
				} else {
					$product_list[$pkey]['pre_name'] = $systematics_arr['data'];
				}
				$library_time = $this->get_library_time($pvalue['createtine']);
				$product_list[$pkey]['library_time'] = $library_time;
			}
			foreach ($product_list as $key => $product) {
				if ($product['thumb_url'] == null) {
					$product_list[$key]['thumb_url'] = $product['pic_url'];
				}
				if($product['is_onsale']==0){
					$product_list[$key]['is_onsale']=2;
				}
				if($product['is_network']==0){
					$product_list[$key]['is_network']=2;
				}
			}
			if (null != input('product_state')) {
				foreach ($product_list as $key => $product) {
					if (input('product_state') == 1) {
						$product_list = array_filter($product_list, function ($p) {return in_array($p['product_state'], [1, 2, 3, 4]);});
					} elseif (input('product_state') == 2) {
						$product_list = array_filter($product_list, function ($p) {return in_array($p['product_state'], [5, 6, 7, 8]);});
					} elseif (input('product_state') == 3) {
						$product_list = array_filter($product_list, function ($p) {return in_array($p['product_state'], [9, 10, 11, 12]);});
					} elseif (input('product_state') == 4) {
						$product_list = array_filter($product_list, function ($p) {return in_array($p['product_state'], [13]);});
					} elseif (input('product_state') == 5) {
						$product_list = array_filter($product_list, function ($p) {return in_array($p['product_state'], [14]);});
					} elseif (input('product_state') == 6) {
						$product_list = array_filter($product_list, function ($p) {return in_array($p['product_state'], [15]);});
					}
				}
			}

			$date = array('code' => 666, 'msg' => '产品列表获取成功', 'data' => ['data' => array_slice($product_list, ($page_current - 1) * 20, 20), 'total' => count($product_list), 'per_page' => 20, 'current_page' => $page_current]);
			IL::insert('log', [
				'user_id' => $this->user_id,
				'operation_user' => $this->user['name'],
				'operation_name' => '查看',
				'operation_content' => '查看产品列表',
				'operation_type' => 1,
				'ip' => Request()->ip(),
				'createtime' => date('Y-m-d H:i:s'),
				'state' => 1,
			]);

		} elseif ($action == 'product_excel') {
			$date = Db::table('product')->alias('p')
				->join('store s', 'p.store_id=s.user_id', 'LEFT')
				->join('product_other po', 'p.id=po.product_id', 'LEFT')
				->join('staff st', 'st.user_id=p.staff_id', 'LEFT')
				->join('business b', 'p.business_id = b.business_id', 'LEFT')
				->where($where)->where(function ($obj) use ($whereor, $subsql) {
					$obj->whereor($whereor)->whereor('p.id', 'in', $subsql);
				})
				->order($order)
				->field($field)
				->select();
		}
		if (input('value_frist')) {
			$user_id = $this->user_id;
			Helptype::search_keyword(input('value_frist'), $user_id);
		}
		return $date;
	}
}
